const db = require('../db/index')

// 添加预约信息的处理函数
exports.createAppointment = async (req, res) => {
    const { doctor_id, patient_id, appointment_date, status, start, end } = req.body
    // 获取客户端提交的预约信息
    const appointInfo = {
        doctor_id: doctor_id,
        patient_id: patient_id,
        appointment_date: appointment_date,
        start: start,
        end: end,
        status: status,
        created_at: new Date().toISOString().slice(0, 19).replace('T', ' ')
    }

    // SQL语句
    const sql = `insert into appointments set ?`

    try {
        // 执行SQL语句
        const result = await new Promise((resolve, reject) => {
            db.query(sql, appointInfo, (err, result) => {
                if (err) reject(err);
                resolve(result);
            });
        });
        
        if (result.affectedRows === 1) {
            res.send({
                status: 0,
                msg: '预约成功！',
            })
        } else {
            res.send({
                status: 1,
                msg: '预约失败，请稍后再试！'
            })
        }
    } catch (err) {
        res.send({
            status: 1,
            msg: err.message || '预约失败'
        })
    }
}

// 获取某日上班的医生
exports.getDoctorsByDate = async (req, res) => {

    const date = new Date(req.body.date);

    // 将日期字符串转换为 Date 对象
    const parsedDate = new Date(date);
    if (isNaN(parsedDate)) {
        return res.status(400).send({
            status: 1,
            msg: '无效的日期格式'
        });
    }

    // 获取星期几的英文缩写
    const day_of_week = new Intl.DateTimeFormat('en-US', { weekday: 'short' }).format(parsedDate);

    // 从请求体中获取 hospital_id 和 specialty
    const { hospital_id, specialty } = req.body;

    // 基本 SQL 查询
    let sql = `
        SELECT d.id, d.name, d.specialty, d.hospital_id, d.position, d.gender
        FROM doctor d
        JOIN worktime da ON d.id = da.doctor_id
        WHERE da.day_of_week = ?
    `;

    // 参数数组
    const params = [day_of_week];

    // 根据是否传入 hospital_id 动态添加查询条件
    if (hospital_id) {
        sql += ' AND d.hospital_id = ?';
        params.push(hospital_id);
    }

    // 根据是否传入 specialty 动态添加查询条件
    if (specialty) {
        sql += ' AND d.specialty = ?';
        params.push(specialty);
    }

    // 执行查询
    db.query(sql, params, (err, result) => {
        if (err) {
            return res.send({
                status: 1,
                msg: '数据库查询错误',
                error: err
            });
        }

        if (result.length === 0) {
            return res.send({
                status: 1,
                msg: '没有医生上班',
                data: result
            });
        }
        return res.send({
            status: 0,
            msg: '查询成功',
            data: result
        });
    });
};

// 获取预约信息
exports.getAppointInfo = async (req,res) => {
    const { patient_id } = req.body

    const sql = `
        SELECT 
            a.id AS appointment_id, 
            a.appointment_date, 
            a.start, 
            a.end, 
            a.status,
            d.name AS doctor_name, 
            d.specialty AS doctor_specialty, 
            h.name AS hospital_name
        FROM appointments a
        JOIN doctor d ON a.doctor_id = d.id
        JOIN hospital h ON d.hospital_id = h.id
        WHERE a.patient_id = ?
        ORDER BY a.appointment_date DESC, a.start DESC
    `;

    try {
        db.query(sql,patient_id,(err,result)=> {
            if(err) {
                res.send({
                    satus: 1,
                    msg: err
                })
            }
            return res.send({
                status: 0,
                msg: '查询成功',
                data: result
            })
        })
    } catch (error) {
        return res.status(500).json({ status: 1, msg: '服务器内部错误' });
    }
}

// 取消预约
exports.cancelAppointment = async (req,res) => {
    const { id } = req.body
    const sql = `UPDATE appointments
        SET status = '已取消', update_at = NOW()
        WHERE id = ?`
    db.query(sql,id,(err,result) => {
        if(err) {
            return res.send({
                status: 1,
                msg: err
            })
        }
        // 检查是否有记录被更新
        if (result.affectedRows > 0) {
            return res.send({
                status: 0,
                msg: '预约已成功取消',
                data: result
            });
        } else {
            return res.status(404).json({
                status: 1,
                msg: '未找到该预约记录'
            });
        }
    })
}

